
const User = require('../models/user');
const Role = require('../models/role');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
require('dotenv').config();

const login = async (email, password) => {
    try {
        const user = await User.findOne({ email });
        const userRole = await Role.findOne({ _id: user.role });
        if (!user) {
            return {
                code:201,
                message:"用户不存在"
            }
        }
        const isMatch = await bcrypt.compare(password, user.password);
        if (!isMatch) {
            return {
                code:201,
                message:"密码错误"
            }
        }
        const token = jwt.sign({ userId: user._id }, process.env.JWT_SECRET, { expiresIn: '1d' }); // 1天有效期
        return {
            code:200,
            data:token,
            message:"登录成功"
        }
    }
    catch (error) {
        return error.message;
    }
}


const addAdminUser = async (userData) => {
    try {
        const hashedPassword = await bcrypt.hash(userData.password, 10);
        const newRole = await Role.create({ name: '超级管理员', description: '系统最高权限，可访问和操作所有功能', active: true, permissions: getAllValues(Role.PERMISSIONS), isAdmin:true });
        userData.role = newRole._id;
        const newUser = await User.create({...userData, password: hashedPassword,name: '管理员' });
        const userRole = await Role.findOne({ _id: newUser.role });
        newUser.roleName = userRole.name;
        return newUser;
    }
    catch (error) {
        return error.message
    }

}

const getAllValues = (obj) => {
    let values = []
    for (let key in obj) {
        console.log(key)
        if (typeof obj[key] === "object") {
            values = values.concat(getAllValues(obj[key]))
        } else {
            values.push(obj[key])
        }
    }
    return values
}
const getUserInfo = async (userId) => {
    try {
        const user = await User.findOne({ _id: userId });
        const currentRole = await Role.findOne({ _id: user.role });
        return {
            id: user._id,
            nickname: user.name,
            username: user.email,
            avatar: user.avatar,
            currentRole:{
                rid: currentRole._id,
                name: currentRole.name,
                description: currentRole.description
            }
        };
    }
    catch (error) {
        return error.message;
    }
}
const decodeToken = (token) => {
    try {
        const decoded = jwt.verify(token, process.env.JWT_SECRET);
        return decoded;
    } catch (error) {
        return null;
    }
}

module.exports = {
  login,
  getUserInfo,
  decodeToken,
  addAdminUser
};
